<?php
namespace app\common\library\util;

use dh2y\qrcode\QRcode;

class PosterUtil{
    public static function createPoster($nickname,$avatar_text,$qrcode_text){
        $posterDefultPath = ROOT_PATH.'public'.config('site.poster');
        $avatarPath = ROOT_PATH.'public'.$avatar_text;
        $qrcodePath = ROOT_PATH.'public'.$qrcode_text;

        //做一张海报 创建图片的实例
        $posterDefultImg = imagecreatefromstring(file_get_contents($posterDefultPath));
        $avatarImg = imagecreatefromstring(file_get_contents($avatarPath));
        $qrcodeImg = imagecreatefromstring(file_get_contents($qrcodePath));
        // return $posterDefultImg;

        //创建一张头像缩略图
        $avatarThumb = imagecreatetruecolor(100, 100);
        imagecopyresampled($avatarThumb, $avatarImg, 0, 0, 0, 0, 100, 100, imagesx($avatarImg), imagesy($avatarImg));

        //二维码图片的宽和高
        list($qrcodeW, $qrcodeH) = getimagesize($qrcodePath);
        // return $qrcodeW;

        //将(二维码、缩略图头像)放到底图上面
        imagecopymerge($posterDefultImg, $qrcodeImg, 70, 250, 0, 0, $qrcodeW, $qrcodeH, 100);
        imagecopymerge($posterDefultImg, $avatarThumb, 50, 40, 0, 0, 100, 100, 100);

        //文字昵称放到底图上面
        $black = imagecolorallocate($posterDefultImg, 0, 0, 0); // 字体颜色
        imagettftext($posterDefultImg, 20, 0, 180, 70, $black, ROOT_PATH.'public/assets/fonts/captcha.ttf', $nickname);

        //保留的文件路径
        $poster_text = '/uploads/qrcode/'.md5($nickname.time()).".jpg";
        $posterPath =  ROOT_PATH."public".$poster_text;
        $result = imagejpeg($posterDefultImg, $posterPath);

        //删除图片、释放资源
        is_file($qrcodePath) && @unlink($qrcodePath);
        $status = ['code'=>0,'msg'=>'海报生成失败'];
        if($result){
            $status['code'] = 1;
            $status['msg'] = $poster_text;
        }
        return $status;
        // imagedestroy($PosterImg);
        // imagedestroy($QrcodeImg);
        // imagedestroy($AvatarImg);
        // imagedestroy($AvatarThumb);
    }
}